﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using QLNhaThuoc.DTO;
using System.Collections;
using QLNhaThuoc.MyClass;

namespace QLNhaThuoc.DAL
{
    class CongTyDA : DataProvider
    {
        private List<IMaObserver> observers; 

        public CongTyDA()
        {
            connect();
            fillMyTable("CONG_TY");
            observers = new List<IMaObserver>();
            AttachObserver(new ThuocDA());
            AttachObserver(new PhieuNhapDA());
        }

        public void insert(CongTy info)
        {
            DataRow row = myTable.NewRow();
            row["MaCT"] = info.MaCT;
            row["Ten"] = info.Ten;
            row["DiaChi"] = info.DiaChi;
            myTable.Rows.Add(row);

            updateMyTable();
        }

        public void delete(CongTy info)
        {
            myTable.Rows.Find(info.MaCT).Delete();

            updateMyTable();
        }

        public void update(CongTy old_info, CongTy info)
        {
            insert(info);
            Notify(old_info, info);
            delete(old_info);
        }

        public void update(CongTy info)
        {
            DataRow row = myTable.Rows.Find(info.MaCT);
            row["Ten"] = info.Ten;
            row["DiaChi"] = info.DiaChi;

            updateMyTable();
        }

        public bool KiemTraPK(CongTy info)
        {
            DataRow row = myTable.Rows.Find(info.MaCT);
            if (row != null)
                return true;
            return false;
        }

        public CongTy[] LayListCongTy()
        {
            ArrayList list = DongHopDuLieuTuDataTable();
            int n = list.Count;
            CongTy[] kq = new CongTy[n];

            for (int i = 0; i < n; i++)
            {
                kq[i] = (CongTy)list[i];
            }

            return kq;
        }

        public override object ConvertOneRowIntoDTO(DataTable myTable, int i)
        {
            CongTy obj = new CongTy();
            obj.MaCT = myTable.Rows[i]["MaCT"].ToString();
            obj.Ten = myTable.Rows[i]["Ten"].ToString();
            obj.DiaChi = myTable.Rows[i]["DiaChi"].ToString();

            return obj;
        }

        public void AttachObserver(IMaObserver observer)
        {
            observers.Add(observer);
        }

        public void DetachObserver(IMaObserver observer)
        {
            observers.Remove(observer);
        }

        public void Notify(CongTy old_info, CongTy info)
        {
            foreach (IMaObserver observer in observers)
            {
                observer.UpdateMaCongTy(old_info, info);
            }
        }
    }
}
